﻿using LineOfBusiness.Controls.Base;
using LineOfBusiness.Core.Base;
using LineOfBusiness.Core.Helper;
using LineOfBusiness.Core.Model;
using LineOfBusiness.Core.Utilities;
using LineOfBusiness.Poco;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LineOfBusiness.Controllers
{
    public class HomeController : LOBController
    {
        public ActionResult Index()
        {
            if (HttpContext.Session["LoginUser"] != null)
            {
                if ((HttpContext.Session["LoginUser"] as LoginUser).MetroStyle)
                    return RedirectToAction("Metro", "Home");
            }

            return View();
        }
        public ActionResult Metro(string module)
        {
            module = string.IsNullOrEmpty(module) ? "AD" : module;
            ViewBag.FunctionGroup = CacheHelper.FunctionList.Values.Where(x => x.FunctionType != "M" && x.IsActive == true && x.ParentID == module).OrderBy(o => o.Sorting).ToList();
            ViewBag.FunctionItem = CacheHelper.FunctionList.Values.Where(x => x.FunctionType != "M" && x.IsActive == true && x.Module == module && x.IsFunction).OrderBy(o => o.Sorting).ToList();
            return View("ModernFunction");
        }

        /// <summary>
        /// Login Action 
        /// </summary>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [Page(LoginRequire = false, FormName = "Login")]
        public ActionResult Login(string returnUrl, string logout)
        {
            ViewBag.Title = "Login";
            ViewBag.logout = logout;
            ViewBag.Metro = "0";
            if (HttpContext.Session["LoginUser"] != null)
            {
                ViewBag.Metro = (HttpContext.Session["LoginUser"] as LoginUser).MetroStyle ? "1" : "0";

                if (string.IsNullOrWhiteSpace(returnUrl) == false)
                    return Redirect(returnUrl);
                else
                    if ((HttpContext.Session["LoginUser"] as LoginUser).MetroStyle)
                        return RedirectToAction("Metro", "Home");
                    else
                        return RedirectToAction("Index", "Home");
            }

            ViewData.Add("cboLg", new List<SelectListItem>() 
            {
                new SelectListItem(){ Value = "EN", Text = "English"},   
                new SelectListItem(){ Value = "VN", Text = "Viet Nam", Selected = true}

            });

            return View();
        }

        [HttpPost]
        [Page(LoginRequire = false, FormName = "Login")]
        public ActionResult Login(string returnUrl, string username, string password,bool again, int PassTime, bool metro, string language)
        {
            string validatorStatus = _Login(username,password,again,PassTime);

            switch (validatorStatus)
            {
                case "1":
                    return Json(new { code = validatorStatus, message = (language == "VN" ? "Tên đăng nhập không được tìm thấy" : "Can not find user in system") });
                case "2":
                    return Json(new { code = validatorStatus, message = (language == "VN" ? "Không thể xác nhận được tên đăng nhập hoặc mật khẩu" : "Invalid username or password. Please try again!") });
                case "3":
                    return Json(new { code = validatorStatus, message = (language == "VN" ? "Người dùng này đã bị khóa" : "User Is Not Active. Please try again!") });
                case "4":
                    return Json(new { code = validatorStatus, message = (language == "VN" ? "Không thể kết nối" : "Can not connect. Please try again!") });
                case "5":
                    return Json(new { code = validatorStatus, message = (language == "VN" ? "Mật khẩu đã hết hạn sử dụng" : "Password had expired and user will deactive?") });
                case "6":
                    return Json(new { code = validatorStatus, message = (language == "VN" ? "Bạn đã nhập sai mật khẩu, tài khoản của bạn sẽ bị khóa" : "You enter wrong password many time and user will deactive?") });
                default:
                    var r = validatorStatus.Split('|');

                    LoginUser loginUser = new LoginUser();
                    loginUser.Administrator = r[0] == "1" ? true : false;
                    loginUser.FirstChange = r[1] == "1" ? true : false;
                    loginUser.CantChange = r[2] == "1" ? true : false;
                    loginUser.Expire = int.Parse(r[3]);
                    loginUser.AlertExpire = r[4] == "1" ? true : false;

                    loginUser.UserID = username;
                    loginUser.UserName = username;


                    loginUser.Language = string.IsNullOrEmpty(language) ? "EN" : language;
                    loginUser.Again = again;

                    if (metro)
                        loginUser.Theme = "metro";
                    else
                        loginUser.Theme = "blueopal";
                    loginUser.IFontSize = 12;
                    loginUser.FontSize = "12px";
                    loginUser.Font = "Arial";
                    loginUser.MetroStyle = metro;
                    // Set login user cache
                    HttpContext.Session["LoginUser"] = loginUser;

                    //Init cache
                    if (CacheHelper.FunctionList.Count == 0)
                        CacheHelper.InitFunctionList();
                    if (CacheHelper.ValueListCache.Count == 0)
                        CacheHelper.InitValueListCache();
                    if (CacheHelper.DataComboBoxInfoCache.Count == 0)
                        CacheHelper.InitDataComboBoxListCache();
                    if (CacheHelper.GridViews.Count == 0)
                        CacheHelper.InitGridViewCache();
                    if (CacheHelper.GridViewSetups.Count == 0)
                        CacheHelper.InitGridViewSetupsCache();
                    if (CacheHelper.MessagesCache.Count == 0)
                        CacheHelper.IniMessagesCache();
                    CacheHelper.InitUserPermission(loginUser);

                    // Set list poco type
                   
                    string url = "";
                    if (metro)
                    {
                        if (Request.Cookies.AllKeys.Contains("lastmodule"))
                            url = Url.Action("metro", "Home", new { module = Request.Cookies["lastmodule"].Value });
                        else
                            url = Url.Action("metro", "Home");
                    }
                    else
                        url = Url.Action("Index", "Home");
                    //if (string.IsNullOrEmpty(returnUrl) == false)
                    //    url = Server.UrlDecode(returnUrl);

                    return Json(new { code = "0", message = url });
            }
        }

        public ActionResult Logout()
        {
            HttpContext.Session.Remove("LoginUser");

            return RedirectToAction("Login", "Home", new { logout = "1" });
        }

        private string _Login(string username, string password, bool again, int PassTime)
        {
            try
            {
                using (LineOfBusiness.DataAccess.EFDALContainer con = new LineOfBusiness.DataAccess.EFDALContainer())
                {
                    var p = con.DBContext.Database.CreateIfNotExists(); 
                    var high = con.Repository.GetOne<AD_tblUserAccountPolicy>(o => 1 == 1);
                    var user = con.Repository.GetOne<AD_tblUserAccount>(o => o.UserGroupID == username && !o.FGroup);
                    if (user == null)
                        return "1";

                    if (!user.FValid)
                        return "3";

                    if ((new LVCrypto()).Decrypt(user.Password) != (password + user.UserGroupID.ToLower()) && again == false)
                    {
                        if (high != null && high.StrongSecurity)
                        {
                            if (PassTime > high.NoOfWrongPwd)
                            {
                                user.FValid = false;
                                con.Repository.Update(user);
                                con.UnitOfWork.SaveChanges();
                                return "6";
                            }
                        }
                        return "2";
                    }

                    var expired = "-1";
                    var alert = "0";
                    if (high != null && high.StrongSecurity && !user.PwdNeverExpire)
                    {

                        alert = high.WarningBeforeExpire.ToString();
                        var his = con.Repository.GetQuery<AD_tblUserAccountPwdHistory>().Where(o => o.UserGroupID == username).OrderByDescending(o => o.DateChanged).Take(1).FirstOrDefault();
                        if (his == null)
                        {
                            expired = high.DaysPwdAge.ToString();
                        }
                        else
                        {
                            DateTime d = new DateTime(his.DateChanged.Value.Year, his.DateChanged.Value.Month, his.DateChanged.Value.Day);
                            d = d.AddDays(high.DaysPwdAge);

                            expired = int.Parse((d - new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day)).TotalDays.ToString()).ToString();
                        }

                        if (int.Parse(expired) <= high.WarningBeforeExpire)
                            alert = "1";
                        if (int.Parse(expired) <= 0)
                        {
                            user.FValid = false;
                            con.Repository.Update(user);
                            con.UnitOfWork.SaveChanges();
                            return "5";
                        }
                    }

                    return (user.FAdm ? "1" : "0") + "|" + (user.MustChangePwd ? "1" : "0") + "|" + (user.CantChangePwd ? "1" : "0") + "|" + expired + "|" + alert;
                }
               
            }
            catch (Exception)
            {
                return "4";
            }

        }

    }
}